(function () {
	var mEditor;
	var DbName = 'DbList';
	var MdThat
	$.MdManager = {
		initMouse(){
			document.oncontextmenu = function (eve) {
					
			};
		},
		initMd: function () {
			MdThat=this
			initMd();
			editormd.prototype.setMdBean= function(arg){
				if( typeof(arg) === "string" ){	
					$.Encryption.MdData.bean=$.Encryption.MdData.creatMdBean(arg,'index','none')
					this.setMarkdown($.Encryption.MdData.bean.data)
				}else{
					$.Encryption.MdData.bean=arg
					this.setMarkdown($.Encryption.MdData.bean.data)
				}
			}
			initJS();
		},
		initCloud() {
			AV.init({
				appId: $.Encryption.Cloud.APP_ID,
				appKey: $.Encryption.Cloud.APP_KEY
			});
			DbName=$.Encryption.CloudTable.MdList;
		},
		scrolTop:function(){
			scrolTop()
		},
		eventManager: function () {
			return eventManager
		},
		loadeMarkDown: function (data) {
			mEditor.setMdBean(data)
		},
		overWatchMd: function (id, data) {
			var div = $("#" + id);
			div.empty();
			editormd.markdownToHTML(id, {
				htmlDecode: true,
				markdown: data,
				GoflowChart:true,
				emoji: true,
				taskList: true,
			});
		},
		loginSucess: function (name) {
			$.Encryption.user.loginSucess(name)
			successMsg("登录成功")
		},
		loginDone: function (data) {
			$.Encryption.user.loginSucess(data)
			
		},
		newPageHelper: function (DbName) {
			return cloudHelp.NewPageHelper(DbName);
		},
		newHelper: function (DbName) {
			console.log("newHelper")
			return cloudHelp.newHelper(DbName);
		},
		newSaveHelper:function(DbName){
			return new cloudHelp.SaveObj(DbName)
		},
		initJS:function(){
			initJS()
		},
		upLoadFC(file,callback){
			upLoadFC(file,callback)
		},
	}
     function initJS(){
		
		String.prototype.contain = function (str) {
			if (str == null || str == "" || this.length == 0 ) {
				return true;
			}
			return this.indexOf(str) != -1 ;  // true
		
		}
		String.prototype.isEmpty = function () {
			if (this == null || this == "" || this.length == 0 ) {
				return true;
			}
			return false
		
		}
		String.prototype.endWith = function (str) {
			if (str == null || str == "" || this.length == 0 || str.length > this.length) {
				return false;
			}
			if (this.substring(this.length - str.length) == str) {
				return true;
			} else {
				return false;
			}
			return true;
		}
		Array.prototype.clone =function(){
			return JSON.parse(JSON.stringify(this))
		}
		Array.prototype.lastItem =function(){
			
			if(this==null||this.length==0){
				return null;
			}
			return this[this.length-1]
		}	
		Array.prototype.remove = function (val) {
			var index = this.indexOf(val);
			if (index > -1) {
				this.splice(index, 1);
			}
		}
		Array.prototype.getValueByColumnName=function(valueName,val){
			let result=null
			
			this.forEach((item, index) => {
				if(item[valueName]==val){
					result=item;
				}
			});
			return result;
		}
		Array.prototype.have=function(valueName,val){
		let result=false;
			this.forEach((item, index) => {
				if(item[valueName]==val){
					result=true;
				}
			});
			return result
		}	
		String.prototype.startWith = function (str) {
			if (str == null || str == "" || this.length == 0 || str.length > this.length) {
				return false;
			}
			if (this.substr(0, str.length) == str) {
				return true;
			}
			else {
				return false;
			}
			return true;
		}

		
		// 对Date的扩展，将 Date 转化为指定格式的String
		// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
		// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
		// 例子： 
		// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
		// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
		Date.prototype.Format = function (fmt) {
			var o = {
				"M+": this.getMonth() + 1, //月份 
				"d+": this.getDate(), //日 
				"H+": this.getHours(), //小时 
				"m+": this.getMinutes(), //分 
				"s+": this.getSeconds(), //秒 
				"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
				"S": this.getMilliseconds() //毫秒 
			};
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
			for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			return fmt;
		}
	 }
	function initMd() {
		// You can custom Emoji's graphics files url path
		editormd.emoji = {
			path: "emoji/emojis/",
			ext: ".png"
		};

		// Twitter Emoji (Twemoji)  graphics files url path    
		editormd.twemoji = {
			path: "emoji/twemoji/36x36/",
			ext: ".png"
		};

		mEditor = editormd("editormd", {
			width: "100%",
			toc: true,
			heightAdapter:true,
			tocDropdown : false,
			emoji: true, // Support Github emoji, Twitter Emoji(Twemoji), fontAwesome, Editor.md logo emojis.
			imageUpload: true,
			flowChart : true,
			// GoflowChart:true,
			taskList: true,
			path: 'lib/',
			onscroll  : function() {},
			onpreviewscroll : function(event) {
				let height=1000;
				if ($('.editormd-preview').scrollTop()>height){
					$("#scrolBtn").fadeIn(500);
				 }else{
					$("#scrolBtn").fadeOut(500);
				 }
	
			},
			upload: function (localFile, callback) {
				// $.Encryption.user.do(function (flag) {
				var mymessage = confirm("此操作将公开您的图片到贴图库?(请勿随意上传)");
				if (mymessage == true) {
					upLoadTieTuku(localFile, callback)
				}
				else if (mymessage == false) {
					callback(false,null)

				}
				//$.MsgBox.Alert('提示',"服务器空间有限暂不对外开放，请使用左侧免费图床");
				//通过leancloud或者贴图库实现图床功能
			},
			// 工具栏添加一个自定义方法
			toolbarIcons: function () {
				// 给工具栏full模式添加一个自定义方法
				var values = ["User", "openFile", "saveBtn", "customIcon", "customIcon1", "cloudSave", "cloudDown",
					"cloudDelet","tuku"
				]
				return values.concat(editormd.toolbarModes.full);
			},
			// 自定义方法的图标 指定一个FontAawsome的图标类
			toolbarIconsClass: {
				customIcon: "fa-paste",
				customIcon1: "fa-paper-plane",
				saveBtn: "fa-floppy-o",
				cloudSave: "fa-cloud-upload",
				cloudDown: "fa-cloud-download",
				cloudDelet: "fa-trash-o",
				openFile: "fa-folder-open",
				User: "fa-user",
				tuku:'fa-magnet'
			},
			// 没有图标可以插入内容，字符串或HTML标签
			toolbarIconTexts: {
				customIcon: "从草稿箱加载"
			},
			// 图标的title
			lang: {
				toolbar: {
					customIcon: "从草稿箱加载",
					customIcon1: "上传图片到第三方图床生成远程链接",
					saveBtn: "保存到本地(ctrl+s)",
					cloudSave: "保存到服务器(最多保存30天)",
					cloudDown: "从服务器读取",
					cloudDelet: "从服务器删除该文章",
					openFile: "打开本地文件",
					User: "超级管理员",
					tuku: "插入图片并上传到贴图库"

				}
			},
			// 自定义工具栏按钮的事件处理
			toolbarHandlers: {
                tuku:function(){

				},
				User: function () {
					eventManager.openMenu();
				},
				openFile: function () {
					eventManager.opnelocalFile(function(result,name){
						mEditor.setMdBean(result)
					});
				},
				customIcon: function () {
					eventManager.getCatch();
				},
				customIcon1: function () {
					eventManager.openCustomerImgBox();
				},
				saveBtn: function () {
					eventManager.downMarkDown();
				},
				cloudDown: function () {
					eventManager.serchCloudFile();

				},
				cloudSave: function () {
					eventManager.UpLoadCloud();

				},
				cloudDelet: function () {
					eventManager.DeletFromCloud();
				}
			},
			onload: function () {
			
				editormd.loadPlugin("plugins/code-auto-save/code-auto-save", function () {
					mEditor.CodeAutoSave();
					
				});

				$("[name='User']").css({
					fontSize: '26px',
					color: '#1E90FF'
				})
				$.Encryption.user.init(); //初始化cookie
				$.Encryption.MdData.setChange(mEditor)//初始化文章


			}
		});

		document.addEventListener('keydown', function (e) {
			if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
				e.preventDefault();
				eventManager.downMarkDown();
				// download("index.md", mEditor.getMarkdown())
			}
		});
	}
	function isSameType(file, type) {
		var Formats = [type];
		return new RegExp("(\\.(" + Formats.join("|") + "))$", "i").test(file.name);
	}

	function upLoadFC(localFile, callback) {
			var file = new AV.File(localFile.name, localFile);
			file.save().then(function (file) {
				callback(true, file.url())
			}, function(err){
				callback(false, null)
				errorMsg('服务器发生错误')
			});
		
		
	}
	function upLoadTieTuku(localFile, callback) {
	
		var formFile = new FormData();
		formFile.append("action", "UploadVMKImagePath"); 
		formFile.append("Token", $.Encryption.TieTuku.token); 			   
		formFile.append("file", localFile); //加入文件对象   file为传递给后台的参数，可以模仿form中input的name值。
		$.ajax({
			url: 'http://up.imgapi.com/',
			type: 'POST',
			
			success: function(data){
				callback(true,data.s_url)
			
			},
			error: function(data){
				callback(false, null)
			},
			data:formFile,
			cache: false,
			contentType: false,
			processData: false
		});
	}
	// function saveCloud() {
		
	// 	// var todo = AV.Object.createWithoutData(DbName, objId);
	// 	// todo.set('data', arg);
	// 	// todo.set('UserId', code);
	// 	// todo.set('name', name);
	// 	// todo.save().then(function (o) {
	// 	// 	successMsg("保存到服务器成功");
	// 	// }, errorCloud);
	// };
	var UserFC = {
		MenuData: [{
			name: '登录超级用户',
			click: function () {
				if ($.Encryption.user.isLogin()) {
					VueData().userBean.loginName = $.Encryption.user.bean.name;
					VueData().userBean.powerLab =$.Encryption.power.number.powerLab[parseInt($.Encryption.user.bean.power)].name

					VueAction.showSuperUser();
				} else {
					VueData().Form.loginForm.dialogVisible = true;
					
				}
				
			}
		},
		{
			name: '打开本地文件',
			click: function () {
				eventManager.opnelocalFile()
			}
		},
		{
			name: '新建Md文件',
			click: function () {
				eventManager.newMd();
			}
		},
		{
			name: 'HTML转MD',
			click: function () {
				VueData().iframeDialogVisible=true;
			}
		},
		{
			name: '开启流程图',
			click: function () {
				VueUI.$confirm('此操作将会造成非chrome内核浏览器异常, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				  }).then(() => {
					mEditor.loadFlowchart()
					mEditor.appendMarkdown('')
					successMsg('开启流程识别成功');
				  }).catch(() => {
					        
				  });
			}
		},
		{
			name: '保存到本地',
			click: function () {
				eventManager.downMarkDown()
			}
		},
		{
			name: '保存到服务器',
			click: function () {
				eventManager.UpLoadCloud()
			}
		},
		{
			name: '打开第三方图床',
			click: function () {
				eventManager.openCustomerImgBox()
			}
		},

		{
			name: '设置',
			click: function () {
			
			}
		},
		{
			name: '退出登录',
			click: function () {
		
				$.Encryption.user.LoginOut();
				VueAction.cleanCatch();
				successMsg('退出登录成功')
			}
		}
		],

	}
	var eventManager = {
		getTime: function (time) {
			return new Date(+new Date(time) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
		},
		getMarkdownData: function (name, code) {
			var mdString = ""
			mdString += "---\n";
			mdString += "type: blog\n ";
			mdString += "title: ";
			mdString += name + "\n ";
			mdString += "categories: Android\n ";
			mdString += "top: true\n ";
			mdString += "tags:\n ";
			mdString += "  - 标签\n";
			mdString += "---\n ";

			mdString += "<!-- more -->\n";
			return mdString;
		},
		wellcomeData: [{
			name: '打开本地Md文档',
			click: function () {
				eventManager.opnelocalFile(function(result,name){
					mEditor.setMdBean(result)
				});
			}
		},
		{
			name: '新建MD文档',
			click: function () {
				eventManager.newMd();
			}
		}
		],

		openMenu: function () {
			var user = $("[name='User']")

			if ($.Encryption.user.isLogin()) {
				UserFC.MenuData[0].name = $.Encryption.user.bean.name;
			} else {
				UserFC.MenuData[0].name = '登录超级用户';
			}
			$.MsgBox.menu(UserFC.MenuData, user.offset().left, user.offset().top)
		},
		newMd: function () {
			$.MsgBox.newMd(function (name, code) {
				if (code == null || code == "") {
					code='none';
				}
				let mdString=eventManager.getMarkdownData(name, code)
				
				mEditor.setMdBean($.Encryption.MdData.creatMdBean(mdString,name,code))

			})
		},
		showUserPage: function () {
			var user = $("[name='User']")
			$.MsgBox.showUserPage(user.offset().top)
		},
		opnelocalFile: function (callback) {
			var fileInput = $("<input type='file'></input>")
			fileInput.bind("change", function () {
				file = fileInput[0].files[0];
				if (isSameType(file, "md")) {
					var reader = new FileReader(); //new一个FileReader实例
					reader.onload = function () {
						callback(this.result,file.name)
					}
					reader.readAsText(file);
				} else {
					errorMsg("格式错误仅支持MD文档")
				}

			});
			fileInput.click();
		},
		serchCloudFile: function () {
			VueAction.showCustomerCloud();
		},
		UpLoadCloud: function () {
			if($.Encryption.getMdData().data.isEmpty()){
				errorMsg("不能上传空的文件");
				return
			}
			if($.Encryption.user.isLogin()){
				VueAction.showUpload();
			}else{
				VueAction.showCustomerUpload();
			}
		},
		DeletFromCloud: function () {
			if ($.Encryption.getMdData().objectId.isEmpty()) {
				errorMsg("本地文件删个吊啊");
				return
			}
			$.MsgBox.Confirm('警告', "将永久从服务器删除", function () {
				new new cloudHelp.SaveObj(VueData().userBean.activeWindow.TableBean.DbName).remove($.Encryption.getMdData());
			})
		},
		downMarkDown: function () {
			download($.Encryption.MdData.bean.name + ".md", mEditor.getMarkdown())
		},
		
		openCustomerImgBox: function () {
			$.MsgBox.Confirm("温馨提示", "免费图床请勿随意上传,(禁止上传色情违禁图片)", function () {
				window.open("https://img.vim-cn.com");
			});
		},
		getCatch: function () {
			mEditor.CodeAutoSaveGetCache();
		}
	}
	
	var cloudHelp = {
		queryinit: function (DbName, page, current, queryName) {
			this.page = page;
			this.current = current;
			this.queryName = queryName;
			this.DbName = DbName;
			this.mQuery = new AV.Query(DbName);
			this.errF=null;
			this.getData = function (callback) {
				if (page) {
					this.mQuery.limit(this.page);
					this.mQuery.skip(this.page * (this.current - 1));
				}
				if(this.errF==null){
					this.errF=errorCloud;
				}
				this.mQuery.addDescending('createdAt');
				this.mQuery.find().then(function (data) {
					
					var json = JSON.parse(JSON.stringify(data));
					callback(json)
				}, this.errF);
				
			};
			this.count = function (callback) {
				let that=this; 
				if(this.errF==null){
					this.errF=errorCloud;
				}
				this.mQuery.count().then(function (count) {
				
					if(that.page){
						callback(Math.ceil(count / page))						
					}else{
						callback(count)
					}
					
				}, this.errF);
			}
			this.equalTo =function(columnName,value){
				this.mQuery.equalTo(columnName, value);
				return this;
			}
			this.contains=function(key,str){
				if(str!=null&&str.trim!=''){
					this.mQuery.contains(key,str);	
				}
				return this;
			}
			this.getQuery = function(){
				return this.mQuery;
			} 

		},
		SaveObj:function(DbName){
			  this.DbName=DbName;
			  this.setObj=function(obj){
				  this.objectBean=JSON.parse(JSON.stringify(obj));
				  return this;
			  }
			 this.remove=function(obj){
				 var todo = AV.Object.createWithoutData(this.DbName, obj.objectId);
				 todo.destroy();
				 successMsg("删除成功");
			 }

			this.save = function (callback) { //callback回调 ，mapObj自定义操作
				if (!this.objectBean) {
					errorMsg('数据对象为空无法保存')
					return
				}
				if(this.errF==null){
					this.errF=errorCloud;
				}
				let id=this.objectBean.objectId;
				var testObject
				if(id){
					testObject = AV.Object.createWithoutData(this.DbName,id);
				}else{
					let TestObject = AV.Object.extend(this.DbName);
					testObject = new TestObject();
				}
				if(this.objectBean){//删除无用字段
					delete this.objectBean.objectId//数据库不允许含有主键字段
					delete this.objectBean.isSet		
					delete this.objectBean.createdAt
					delete this.objectBean.updatedAt
					delete this.objectBean.timeString
					delete this.objectBean.temp
					delete this.objectBean.tableName
					
					
				}
					testObject.save(this.objectBean).then(function (this_obj) {
						
						if(callback)
						callback(this_obj)
					}, this.errF)
			}
		},
		
		NewPageHelper(DbName) {
			return new cloudHelp.queryinit(DbName, 5, 1, '')
		},
		newHelper(DbName) {
			return new cloudHelp.queryinit(DbName)
		}
	}


	var successMsg = function (msg) {
		VueUI.$message({
			message: msg,
			type: 'success'
		});

	}
	var errorMsg = function (msg) {
		VueUI.$message.error(msg);

	}
	var errorCloud = function (err) {
		console.err(err)
		VueUI.$notify.error({
			title: '错误',
			message: '服务器发生错误已自动保存本地草稿箱，稍后重试'
		});

	}
	function scrolTop(){
	 $(".editormd-preview").scrollTop(0);
	 $(".CodeMirror-scroll").scrollTop(0);
	}
	function download(filename, text) {
		if(text==null||text.trim()==''){
			errorMsg('都没有数据保存个JJ啊')
			return
		}
		var element = document.createElement('a');
		element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
		element.setAttribute('download', filename);

		element.style.display = 'none';
		document.body.appendChild(element);

		element.click();

		document.body.removeChild(element);
	}
})();
